import unittest

import mybatis_mapper2sql

import mybatis_patch
from ddl_parser import TableInfoMgr
from log import LOGGER, WORK_DIR
from sql_checker import SQLChecker

mybatis_patch.patch()


class MybatisMapperChecker:
    def __init__(self, xml_path, tbl_mgr: TableInfoMgr):
        self.xml_path = xml_path
        self.sql_checker = SQLChecker(tbl_mgr)

    def check(self):
        hints = []
        sql_list = self.parse_mapper_xml(self.xml_path, hints)

        for sql_map in sql_list:
            for k in sql_map:
                self.check_i(k, mybatis_patch.post_process(sql_map[k]), hints)
        return hints

    def parse_mapper_xml(self, xml_path, hints: list):
        mapper, _ = mybatis_mapper2sql.create_mapper(xml=xml_path)
        return mybatis_mapper2sql.get_statement(mapper, result_type="list")

    def check_i(self, sql_id, sql, hints: list):
        try:
            chk_res = self.sql_checker.check(sql)

            for err in chk_res:
                hints.append("sqlId:%s %s" % (sql_id, err))
        except Exception as e:
            hints.append("sqlId:%s error:%s" % (sql_id, str(e)))
            LOGGER.error(
                "parse sqlId:%s error:%s, sql statement:%s" % (sql_id, str(e), sql)
            )


class MybatisParserTest(unittest.TestCase):
    TEST_MAPPER_PATH = "%s/dt/data/TestMapper.xml" % WORK_DIR

    def test(self):
        checker = MybatisMapperChecker(self.TEST_MAPPER_PATH, TableInfoMgr())
        hints = checker.check()
        self.assertEqual(len(hints), 1)


if __name__ == "__main__":
    unittest.main()
